package com.d.common.config.mybatis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by
 */
@Configuration
public class DataSourceConfiguration {

    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;


    /**
     * erp数据
     *
     * @return
     */
    @Bean(name = "userDS")
    @ConfigurationProperties(prefix = "spring.datasource.user")
    public DataSource userDS() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    //当相同类型的实现类存在时，选择该注解标记的类
    @Bean("dynamicDS")
    @Primary
    public DataSource dynamicDS() {
        MyAbstractRoutingDataSource dds = new MyAbstractRoutingDataSource(0);
        dds.setDefaultTargetDataSource(userDS());
        Map<Object, Object> dsMap = new HashMap<>();
        dsMap.put("userDS", userDS());
        dds.setTargetDataSources(dsMap);
        return dds;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dynamicDS());
    }

    //这里的JdbcTemplate构造参数同样需要一个DataSource,为了实现数据源切换查询，
    //这里使用的也是dynamicDS这个bean
    @Bean(name = "jdbcTemplate")
    public JdbcTemplate getJdbc() {
        return new JdbcTemplate(dynamicDS());
    }
}
